﻿using AutoMapper;
using MediatR;
using S.Authorization.Common;
using S.Authorization.Common.Dto;
using S.Authorization.Domain.Model.Authority;
using S.Authorization.Infrastructure.Interface.Role;
using S.Authorization.Read.API.Application.Command.RoleCommand;
using System.Collections.Generic;
using static S.Authorization.Read.API.Application.Command.RoleCommand.RoleReadAllCommand;

namespace S.Authorization.Read.API.Application.CommandHandlers.RoleCommandHandler
{
   
    public class RoleReadAllCommandHandler : IRequestHandler<RoleGetByIdCommand, RoleModelByRIdDto>, IRequestHandler<RoleGetPageAllCommand, Pager<RoleModel>>,IRequestHandler<RoleGetAllCommand,List<RoleModel>>
    {
        #region 注入
        private readonly IRoleRepository repository;
        private readonly IMapper mapper;

        public RoleReadAllCommandHandler(IRoleRepository repository,IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }
        #endregion


        /// <summary>
        /// 角色表反填
        /// </summary>
        public async Task<RoleModelByRIdDto> Handle(RoleGetByIdCommand request, CancellationToken cancellationToken)
        {
            RoleModel roleModel=await repository.GetByIdAsync(request.RoleId);
            return mapper.Map<RoleModelByRIdDto>(roleModel);
        }

        /// <summary>
        /// 角色表分页显示查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Pager<RoleModel>> Handle(RoleGetPageAllCommand request, CancellationToken cancellationToken)
        {
            List<RoleModel> roleList = await repository.GetAllAsync();
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                roleList = roleList.Where(x => x.RoleName.Contains(request.RoleName)).ToList();
            }
            int totalCount = roleList.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            roleList = roleList.OrderBy(x => x.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return new Pager<RoleModel>()
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                resultData = roleList
            };
        }
        /// <summary>
        /// 角色显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<RoleModel>> Handle(RoleGetAllCommand request, CancellationToken cancellationToken)
        {
            return await repository.GetAllAsync();
        }
    }
}
